package com.lgz.lgzapiclient.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.lgz.lgzapiclient.model.User;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import static com.lgz.lgzapiclient.utils.SignUtils.getSige;

public class LgzApiClient {

    private String accessKey;

    private String secretKey;

    public LgzApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    /**
     * get请求
     * @param name
     * @return
     */

    public String getNameByGet(String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result3 = HttpUtil.get("http://localhost:8123/api/name/get", paramMap);
        System.out.println(result3);
        return result3;
    }

    /**
     * post请求
     * @param name
     * @return
     */

    public String getNameByPost(String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result3 = HttpUtil.post("http://localhost:8123/api/name/post", paramMap);
        System.out.println(result3);
        return result3;
    }

    /**
     *
     * @param body
     * @return
     */

    private Map<String, String> getHeaderMapper(String body) {
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("accessKey", accessKey);                                                   // 访问密钥
//        headers.put("secretKey", secretKey);                                                 // 秘钥   一定不能发送后端
        hashMap.put("nonce", RandomUtil.randomNumbers(4));                            // 随机数
        hashMap.put("body", body);                                                             // 请求体
        hashMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000 ));        // 时间戳
        hashMap.put("sign", getSige(body, secretKey));                                      // 签名
        return hashMap;
    }

    /**
     * json对象
     * @param user
     * @return
     */

    public String getUsernameByPost(User user) {
        String json = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post("http://localhost:8123/api/name/user")
                .charset(StandardCharsets.UTF_8)
                .addHeaders(getHeaderMapper(json))    //添加请求头
                .body(json)
                .execute();
        System.out.println(httpResponse.getStatus());
        String body = httpResponse.body();
        return body;
    }
}
